﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Icoders.MarketTracker.Core.MasterData;
using Icoders.MarketTracker.Core.Repository.MasterDataRepositories;
using Icoders.MarketTracker.Core.Validation;
using Icoders.MarketTracker.Web.Lib.Services;
using Icoders.MarketTracker.Web.Lib.Validation;

namespace Icoders.MarketTracker.Web.Areas.Admin.Controllers
{
    [Authorize(Roles = "admin")]
    public class UserController : Controller
    {
        //
        // GET: /Admin/User/

        private IUserRepository _userRepository;
        private IDropDownService _dropDownService;

        public UserController(IUserRepository userRepository, IDropDownService dropDownService)
        {
            _userRepository = userRepository;
            _dropDownService = dropDownService;
        }

        public ActionResult Index()
        {
            var item = _userRepository.GetAll();
            return View(item);
        }
        public ActionResult Create()
        {
            Bind();
            return View(new User());
        }

        private void Bind()
        {
            ViewBag.UserTypeList = _dropDownService.EnumToList<UserType>();
        }

        [HttpPost]
        public ActionResult Create(User model)
        {
            try
            {
                model.Password = "1234";
               
                _userRepository.Save(model);
            }catch(DomainValidationException dve)
            {
                Bind();
                ValidationSummary.DisplayDomainValidationResult(dve, ModelState);
                return View(model);
            }
            catch(Exception ex)
            {
                Bind();
                ValidationSummary.DisplayValidationResult(ex.Message, ModelState);
                return View(model);
            }
            return RedirectToAction("Index");
        }
        public ActionResult Edit(int id)
        {
            Bind();
            var model = _userRepository.GetById(id);
            return View(model);
        }
        [HttpPost]
        public ActionResult Edit(User model)
        {
            try
            {
                _userRepository.Save(model);
            }
            catch (DomainValidationException dve)
            {
                Bind();
                ValidationSummary.DisplayDomainValidationResult(dve, ModelState);
                return View(model);
            }
            catch (Exception ex)
            {
                Bind();
                ValidationSummary.DisplayValidationResult(ex.Message, ModelState);
                return View(model);
            }
            return RedirectToAction("Index");
        }
    }
}
